<?php
class Badwords{
	private static $instance = NULL;
	
	private $badwordInput = array();
	private $badwordReplace = array();
	
	/**
	 * Konstruktor
	 */
	private function __construct() {}
	private function __clone() {}
	
	public static function getInstance() {
		if(self::$instance === null) {
			self::$instance = new Badwords;
			self::$instance->initBadwords();
		}
		return self::$instance;	
	}
	
	public function initBadwords() {
		$badwords = Badwords::getBadwords();
		foreach($badwords as $b) {
			$this->badwordInput[] = $b['badInput'];
			$this->badwordReplace[] = $b['badReplace'];
		}
	}
	
	public static function getBadwords() {
		$badwords = array();
		$query = DB::getInstance()->query("
			SELECT
				id,
				badInput,
				badReplace
			FROM
				".Tables::$badwordsTbl);
		while($b = DB::getInstance()->fetchAssoc($query)) {
			$badwords[] = $b;
		}
		return $badwords;
	}
	
	public function getBadword($id) {
		if(!is_numeric($id)) exit;
		
		$query = DB::getInstance()->query("
			SELECT
				id,
				badInput,
				badReplace
			FROM
				".Tables::$badwordsTbl."
			WHERE
				id = '".$id."'");
		$badword = DB::getInstance()->fetchAssoc($query);
		return $badword;
	}
	
	public function addBadword($input,$replace) {
		DB::getInstance()->query("
			INSERT INTO
				".Tables::$badwordsTbl."
			SET
				badInput = '".DB::parseVar($input)."',
				badReplace = '".DB::parseVar($replace)."'");
	}
	
	public function editBadword($id,$input,$replace) {
		if(!is_numeric($id)) exit;
		
		DB::getInstance()->query("
			UPDATE
				".Tables::$badwordsTbl."
			SET
				badInput = '".DB::parseVar($input)."',
				badReplace = '".DB::parseVar($replace)."'
			WHERE
				id = '".$id."'");
	}
	
	public function deleteBadword($id) {
		if(!is_numeric($id)) exit;
		
		DB::getInstance()->query("
			DELETE FROM
				".Tables::$badwordsTbl."
			WHERE
				id = '".$id."'");
	}
	
	public function parse($text) {
		$text = str_replace($this->badwordInput,$this->badwordReplace,$text);
		return $text;
	}
}
?>